package scau.mis4.chanyulin.atm.physical;

import scau.mis4.chanyulin.atm.base.common.CODE;
import scau.mis4.chanyulin.atm.base.system.ConfigConst;
import scau.mis4.chanyulin.atm.base.system.DbService;
import scau.mis4.chanyulin.atm.domain.Account;
import scau.mis4.chanyulin.atm.domain.Card;

/**
 * Created by chanyulin on 2018/5/24.
 * 读卡器
 */
public class CardReader {

    // 保存已插入的卡
    private Card insertedCard;
    // 数据库服务
    private DbService dbService;
    // 保存已退出的卡
    private static Card ejectedCard;

    public CardReader() {
        insertedCard = null;
        ejectedCard = null;
        dbService = new DbService();
    }

    /**
     * 插卡
     * @param card
     * @return
     */
    public int insertCard(Card card) {
        if (null == card) return CODE.ERR_NULL_POINTER;

        // 判断是否已有卡插入
        if (null == insertedCard) {
            // 校验
            boolean vertifyResult = vertifyCard(card);
            if (vertifyResult) {
                insertedCard = card;
                return CODE.MSG_SUCCESS;
            }
        }
        return CODE.MSG_FAILED;
    }

    /**
     * 校验卡
     * @param card
     * @return
     */
    public boolean vertifyCard(Card card) {
        return card.getCompany() == ConfigConst.THIS_BANK_COMPANY && card.getCardId() != null;
    }

    /**
     * 读卡
     * @return
     */
    public Account readCard() {
        return dbService.findAccount(insertedCard.getCardId());
    }

    /**
     * 退卡
     * @return
     */
    public int ejectCard() {
        if (null == insertedCard) return CODE.ERR_NULL_POINTER;

        ejectedCard = insertedCard;
        insertedCard = null;
        return CODE.MSG_SUCCESS;
    }

    /**
     * 取卡
     * @return
     */
    public static Card takeCard() {
        if (null == ejectedCard) return null;

        Card cardToTake = ejectedCard;
        ejectedCard = null;
        return cardToTake;
    }


}
